/**
 * 秒杀2.0js管理
 */

var _data,_i= 1,_n= 1,_m=1;
$(function () {

    //添加活动
    $('.checkSubmit').click(function () {
        var citylist = [];
        var gift = {};
        var  _obj = $(this);
        var _data={};
        if(!checkVailForm()){
            return false;
        }else{
            _data = checkVailForm();
        }

        //组合场次
        var _cityLength,_timeLength,_timesLength;

        _cityLength = _obj.parents('.Jactadd').find('.CitySelectInfo .picdemo').length; //城市
        _timeLength = _obj.parents('.Jactadd').find('.Timeslot .TimeSoltInfo').length;  //日期段
        _timesLength = _obj.parents('.Jactadd').find('.timeTimeslot .TimeSoltTimesInfo').length;

        if(_cityLength<1 || _timeLength<1 || _timesLength<1) return !1;

        //城市
        $('input.cityinput').each(function(i, e) {
            if($(e).val()==''){
                standardTips('城市不能为空');
                return false;
            }
            citylist.push($(e).val())
        });


        //日期
        var timeRange = [];
        var dateRange = [
            $('input.starttime:eq(0)').val().replace(/\-|\:|\s+/g, '').substring(0, 8),
            $('input.endtime:eq(0)').val().replace(/\-|\:|\s+/g, '').substring(0, 8),
        ];


        //时间段
        $('input.startplaytimes').each(function(j,k){
            var startpaly = $(k).val().replace(/\:/g, '')+'00';
            var endplay = $('input.endplaytimes:eq('+j+')').val().replace(/\:/g, '')+'00';
            timeRange.push([startpaly,endplay]);

        })

        //奖品和库存
        $('div.goods-list').each(function(i, target) {
            var city = $(target).data('city');
            if (!gift[city]) gift[city] = [];
            $(target).find('input.prizeid').each(function(n, e) {
                var stack = {};
                stack.couponid = parseInt($(e).val());
                stack.amount = $(target).find('input.prize-number:eq('+n+')').val();
                //console.log(stack);
                gift[city].push(stack);
            });
        });

        _data.timeRange = JSON.stringify(timeRange);
        _data.dateRange = JSON.stringify(dateRange);
        _data.citylist = JSON.stringify(citylist);
        _data.gift = JSON.stringify(gift);
        //console.log(citylist);
       // console.log(dateRange);
       // console.log(timeRange);
        //console.log(gift);

        console.log(_data);

        return;
        $.post(addacturl, _data, function (data) {
            console.log(data);
            if (data.errno == 0) {
                standardTips('上传成功', 2);
               // window.location.href = editacturl + "&ActivityID=" + data.data.Activity.ActivityID+'&AttributeID='+data.data.Activity.attrbuteID;
            } else {
                standardTips('添加失败', 2);
            }
        }, 'json')
    })



    //加载更多
    var page = 2;
    $('.JMoreActivity').click(function () {
        var _html = '';
        $.ajax({
            url: getMoreActicityUrl,
            type: 'post',
            data: {Page: page},
            timeout: 15000,
            dataType: "json",
            beforeSend: function (XMLHttpRequest) {
                $(".JMoreActivity").html("加载中……");
            },
            success: function (data, textStatus) {
                console.log(data);
                if (data.errno == 0) {
                    if (data.data.package.length > 0) {
                        $.each(data.data.package, function (key, val) {
                            _html += '<tr>' +
                                '<td><input type="checkbox" data-id=""></td>' +
                                '<td class="act-name">' + val.Name + '<a class="act-view" href="' + getViewUrl + '&ChannelId=' + val.ChannelId + '"></a></td>' +
                                '<td>' + val.ChannelId + '</td>' +
                                '<td>' + val.ExpirationTime + '</td>' +
                                '<td>' + val.View + '</td>' +
                                '<td>' + val.WeiXinUrl + '</td>' +
                                '<td>' + val.UpdateTime + '</td>' +
                                '<td>1个链接 <a href="javasctipt:void(0)" class="Jcopy" data-href="">（查看链接）</a>';
                            _html += ' <input type="hidden" value="' + val.url + '" class="hidUrl">';
                            _html += '</td>';
                            _html += '</tr>';
                        })
                        $('.Joperate tbody').append(_html);
                        $(".JMoreActivity").html("加载更多渠道包链接");
                    } else {
                        $('.JMoreActivity').text('没有更多数据……');
                    }

                }
            },
            complete: function (XMLHttpRequest, textStatus) {
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(".JMoreActivity").html('加载失败,<a href="#" class="JMoreActivity">点击重试</a>');
            }
        });
        page++;
    });

    //点击奖品展示类型
    //图片
    //$('.addPicShow').click(function(){
    //    $(this).parents('.addPrizePic ').addClass('addpricebigborder');
    //    $(this).parents('.addPrizePic ').next().removeClass('addpricebigborder');
    //})
    ////图文
    //$('.addTextPicShow').click(function(){
    //    $(this).parents('.addPrizePic ').addClass('addpricebigborder');
    //    $(this).parents('.addPrizePic ').prev().removeClass('addpricebigborder');
    //})

    //添加奖品类型
    $('.JsavePrize').click(function(){
        var _type;
        _type = $('.addpricebigborder').find('a').data('pictype');
        if(!_type){
            standardTips('请选择奖品展示类型');
            return false;
        }
        console.log(_type);
        $('.prizetype').val(_type);
        $('#closePushPrizeBtn').trigger('click');

    })

    //添加奖品
    $('.Jaddvisit').click(function(){
        var _type,_html='';
        //展示类型存在，不显示弹出框
        _type =  $('.prizetype').val();
        //添加，展示添加的数据
        _html += '<div class="prize-info"> <div class="Jcitygarbinfo"> ' +
            '<div class="del-play"><a href="javascript:;">删除</a></div> ' +
            '<div class="control-group"> ' +
            '<label class="control-label ">奖品标题：</label> ' +
            '<div class="controls"> <input type="text" name="prize_name" class="prize_name"> </div> </div>' +
            ' <div class="control-group">' +
            '<label class="control-label">奖品icon：</label> ' +
            '<div class="controls"> ' +
            '<div id="coverImgInfo">' +
            '<form id="imgForm" action="' + ajaxPic + '" method="post"enctype="multipart/form-data">' +
            '<input type="file" id="coverImg" name="coverImg" accept="image/*" onChange="coverImgChange(this);">' +
            '<span id="coverShopImg"></span></form>' +
            '<input type="hidden" name="ShopPic" class="shoppic" id="shoppic"></div>' +
            '</div> </div> ' +
            '<div class="control-group"> ' +
            '<label class="control-label">试用分店：</label>' +
            '<div class="controls"> ' +
            '<textarea name="branchshop" class="branch-shop" >' +

            '</textarea>' +
            '<span class="dist-info"><a class="btn btn-danger Jdist">识别</a></span>' +
            '<div class="list-group dist-list">' +
            '</div> ' +
            '</div> </div>';

        //<!--其他-->
        _html += '<div class="control-group"> <label class="control-label">其他：</label>' +
            '<span class="add-prize"> ' +
            '<a href="javascript:void(0)" class="btn btn-info Jaddprize">+添加奖品字段</a> ' +
            '</span>' +
            '<div class="prize-deatillist"> ' +
            ' </div> </div> </div></div>';
        $('.prizeinfores').prepend(_html);
        $('.busnum').text(_i);
        _i++;
        console.log(_i);


    })

    //删除奖品
    $('.prizeinfores').on('click','.prize-info .del-play a',function(){
        var _obj = $(this),_num;
        standardConfirm('确定删除',function(){
            //删除节点
            _obj.parents('.prize-info').remove();

            //数量
             _num = $('.busnum').text();
            var _nu = _num - 1;

            $('.busnum').text(_nu);

            if(_nu==0){
                _i = 1;
            }else{
                _i = _nu+1;
            }
        })

    })

    //识别分店id
    $('.prizeinfores').on('click','.prize-info .Jdist',function(){
        var _obj = $(this),_branchid,_html='',textval;
        _branchid = $.trim(_obj.parents('.prize-info').find('.branch-shop').val());

        textval = _obj.parents('.prize-info').find('.branch-shop').val();

        var textlist = textval.split("\n");
        console.log(textlist);
        $.post(ajaxGetBrach,{branchid:_branchid},function(data){

            if(data.data.list.length>0){
                $.each(data.data.list,function(i,n){
                    var flagbranch = false;
                    $.each(textlist,function(v,m){
                        if (n.ShopID == m) {
                            flagbranch = true;
                        }
                    });
                    if(flagbranch){
                        _html+= '<a href="#" class="list-item" data-city="'+ n.City+'" data-shopid="'+ n.ShopID+'">'+ n.ShopName+'</a>';
                    }else{
                        _html+= '<a href="#" class="list-item" data-city="" data-shopid="">无法识别的分店id</a>';
                    }
                })

                _obj.parents('.prize-info').find('.dist-list').html(_html);
            }
           // console.log(data);
        },'json')
        //console.log(_branchid);
    })

    //添加奖品字段弹出参数传递
    $('.prizeinfores').on('click','.prize-info .Jaddprize',function(){
        var _obj = $(this),_html='';

        _html+='<div class="control-group font-group-res"> ' +
                '<div class="fontfield">' +
                '<span class="fieldname">添加奖品字段</span>' +
                '</div>'+
                '<div class="fontinput">'+
                '<div><input type="text" name="fontName" class="fontName"></div>' +
                '<div><textarea class="fontContent"></textarea>' +
                '<a href="javascript:void(0)"><img src='+RESOURCE_URL+'/images/del.png></a>'+
                '</div></div>'+

            '</div>';
        _obj.parents('.prize-info').find('.prize-deatillist').append(_html);

        console.log(111);
    })

    //删除添加字段
    $('.prizeinfores').on('click','.prize-info .prize-deatillist img',function(){
        var _obj = $(this);
        standardConfirm('确定删除',function(){
            //删除节点
            _obj.parents('.font-group-res').remove();
        })

    })




    //添加字段

    $('.JsaveFontInfo').click(function(e){
        var _html='',_obj;
        var fontName = $('.fontName').val();
        _obj = $('.fontObj').val();
        console.log(_obj);
        if(!checkName(fontName)){
            standardTips('填写字段名');
            return false;
        }
        var fontContent = $('.fontContent').val();
        if(!checkName(fontContent)){
            standardTips('填写字段内容');
            return false;
        }

        _html+='<div class="controls"><span class="prize-detail"><i class="prizefontname">'+fontName+'</i>/<i class="prizefontcontent">'+fontContent +
            '</i>（<a href="#" class="del-prize">删除</a> . <a href="#" class="edit-prize">编辑</a>）</span> ' +
            '</div>';

        $('#closePushPrizedetailBtn').trigger('click');
        $('.fontName').val('');
        $('.fontContent').val('');
        _obj.parents('.prize-info').find('.prize-deatillist').append(_html);
    })



    //添加场次城市
    $('.JactivityTotal').on('click','.addVisit',function(){
        var _obj = $(this),_html='';
        m++;
        _html+='<span class="picdemo"> <input type="text" class="cityinput" id="citySelect'+m+'" placeholder="请输入城市"> ' +
            '<a href="javascript:void(0)"><img src="/public/images/del.png"></a></span>';
        _obj.parents('.Jmanyactivity').find('.CitySelectInfo').append(_html);
        new Vcity.CitySelector({input:'citySelect'+m});

    })


    //删除场次城市
    $('.JactivityTotal').on('click','.CitySelectInfo .picdemo img',function(){
        console.log(111);
        var _obj = $(this);
        standardConfirm('删除城市，将删除该城市相关所有时段活动场次，确认删除？',function(){
            //删除节点
            _obj.parents('.picdemo').remove();
        })
    })


    //添加场次活动时间段
    $('.JactivityTotal').on('click','.addTime',function(){
        console.log(1234);
        var _obj = $(this),_html='' , _time="laydate({format: 'YYYY-MM-DD'})";
        _html+='<div class="controls TimeSoltInfo">'+
            '<input type="text" name="ExpirationTime" class="starttime" placeholder="请选择开始时间" onclick="'+_time+'">' +
            ' 至 ' +
        '<input type="text" name="ExpirationTime" class="endtime" placeholder="请选择结束时间" onclick="'+_time+'">'+
           ' <a href="javascript:void(0)"><img src="/public/images/del.png"></a> </div>';

        _obj.parents('.Jmanyactivity').find('.Timeslot').append(_html);
    })

    //添加场次活动场次时间段
    var k=1;
    $('.JactivityTotal').on('click','.addTimesTime',function(){
        var _obj = $(this),_html='';
        _html+='<div class="controls TimeSoltTimesInfo">'+
            '<input type="text" name="ExpirationTime" class="startplaytimes starttimestime'+k+'" placeholder="请选择开始时间" value="" data-autoclose="true">' +
            ' 至 ' +
            '<input type="text" name="ExpirationTime" class="endplaytimes endtimestime'+k+'" placeholder="请选择结束时间" value="" data-autoclose="true">'+
            ' <a href="javascript:void(0)"><img src="/public/images/del.png"></a> </div>';
        _obj.parents('.Jmanyactivity').find('.timeTimeslot').append(_html);

        $('.starttimestime'+k).clockpicker();
        $('.endtimestime'+k).clockpicker();
        k++;
    })

    //删除场次时间段
    $('.JactivityTotal').on('click','.TimeSoltTimesInfo img',function(){
        var _obj = $(this);
        standardConfirm('删除时段，将删除该该时段相关所有城市活动场次，确认删除？',function(){
            //删除节点
            _obj.parents('.TimeSoltTimesInfo').remove();
        })

    })

    //删除场次添加字段
    $('.JactivityTotal').on('click','.Timeslot img',function(){
        var _obj = $(this);
        standardConfirm('删除时段，将删除该该时段相关所有城市活动场次，确认删除？',function(){
            //删除节点
            _obj.parents('.TimeSoltInfo').remove();
        })

    })

    //活动城市和活动时段填写好之后，点击识别
    $('.JactivityTotal').on('click','.Distinguish a',function(){
        var _obj = $(this),_html='',_cityLength,_timeLength,_timesLength;

        _cityLength = _obj.parents('.JactivityPlayInfo').find('.CitySelectInfo .picdemo').length; //城市
        _timeLength = _obj.parents('.JactivityPlayInfo').find('.Timeslot .TimeSoltInfo').length;  //日期段
        _timesLength = _obj.parents('.JactivityPlayInfo').find('.timeTimeslot .TimeSoltTimesInfo').length;


        if(_cityLength>0&&_timeLength>0&&_timesLength>0){

            var citylist = [];
            $('input.cityinput').each(function(i, e) {
                if($(e).val()==''){
                    standardTips('城市不能为空');
                    return false;
                }
                citylist.push($(e).val())
            });

            var timeRange = [];
            var dateRange = [
                $('input.starttime:eq(0)').val().replace(/\-|\:|\s+/g, '').substring(0, 8),
                $('input.endtime:eq(0)').val().replace(/\-|\:|\s+/g, '').substring(0, 8),
            ];


//            $('input.starttime').each(function(i, e) {
//
//                var startT = $(e).val();
//                var endT = $('input.endtime:eq('+i+')').val();
//
//                timeRange.push([startT,endT]);
//
//
//            });

            $('input.startplaytimes').each(function(j,k){
                var startpaly = $(k).val().replace(/\:/g, '');
                var endplay = $('input.endplaytimes:eq('+j+')').val().replace(/\:/g, '');

               // var startT = $(k).parents('.addPlay').find('.Timeslot .starttime').val();
                //var endT = $(k).parents('.addPlay').find('.Timeslot .endtime:eq('+j+')').val();

                var startT = $('input.starttime').val();
                var endT = $('input.endtime').val();

                var timesplay = $(k).val();
                var endtimesplay = $('input.endplaytimes:eq('+j+')').val()

                timeRange.push([startpaly,endplay,startT,endT,timesplay,endtimesplay]);

            })

            console.log(timeRange);


            $.each(citylist, function(k,v) {
                $.each(timeRange, function(a,b) {
                   // console.log(b);
                    _html+='<div class="editActivitydetail goods-list" data-timeid="'+a+'" data-city="'+v+'"> ' +
                        '<div class="actdetail"> <span class="survey">编辑活动场次详情</span> </div> ' +
                        '<div class="control-group act-border"> ' +
                        '<div class="prize-time">  <span>'+v+' / '+b[2] +'至'+ b[3]+' － '+ b[4] +'至'+ b[5]+'</span></div> ' +
                        '<div class="editaddprizelist"> <label class="control-label">奖品：</label> <div class="controls"> ' +
                        '<div class="editPrizeinfo"> <a href="javascript:void(0)" class="JeditaddPrize">添加奖品</a> </div> ' +
                        '<div class="editActivityPrizeList">' +
                        '</div> </div> </div> </div>';
                    _html+='</div>';
                });
            });

            $('.playnuminfo').text(_timeLength);  //场次数量
            _obj.parents('.JactivityPlayInfo').find('.activityNumber').html(_html);
        }


    })

    //添加活动场次添加奖品
    $('.JactivityTotal').on('click','.activityNumber .JeditaddPrize',function(){
        var _obj=$(this),_html='';

        _html+='<div class="editPrizelist"> ' +
            '<input type="text" name="name" placeholder="奖品id" class="prizeid"> ' +
            '<input type="text" name="name" class="prize-number" placeholder="数量" class="prizemun"> ' +
            '<a href="javascript:void(0)"><img src="/public/images/del.png"></a>' +
            ' </div>';
        _obj.parents('.editaddprizelist').find('.editActivityPrizeList').append(_html);
    })

    //删除活动场次添加奖品
    $('.JactivityTotal').on('click','.activityNumber .editPrizelist a',function(){
        var _obj = $(this);
        standardConfirm('确定删除',function(){
            //删除节点
            _obj.parents('.editPrizelist').remove();
        })
    })

    //控制键盘输入奖品id和数量

    $('.JactivityTotal').on('keyup','.editActivityPrizeList .editPrizelist input',function(){
        $(this).val($(this).val().replace(/[^0-9.]/g, ''));
    })

    //提交场次
    $('.Jaddsubmit').click(function(){

        var gift = {};
        var amount = [];
        var citylist = [];
        var prizename=[];
        var icon=[];
        var shopid=[];
        var field = [];
        var fieldContent = [];

        var ActivityID = $('.ActivityID').val();
        var AttributeID = $('.AttributeID').val();
        //奖品
        $('.prizeinfores .prize-info').each(function(a,b){

            field[a] = [];
            prizename.push($(b).find('.prize_name').val());
            icon.push($(b).find('.shoppic').val());
            var shop = $.trim($(b).find('.branch-shop').val());

            shopid.push(shop.split("\n"));


            $(b).find('.font-group-res').each(function(m,r){

                field[a].push($(r).find('.fontName').val());
                field[a].push($(b).find('textarea.fontContent:eq('+m+')').val());
            })
        })

        $('input.cityinput').each(function(i, e) {
            if($(e).val()==''){
                standardTips('城市不能为空');
                return false;
            }
            citylist.push($(e).val())
        });

        var timeRange = [];
        var dateRange = [
            $('input.starttime:eq(0)').val().replace(/\-|\:|\s+/g, '').substring(0, 8),
            $('input.endtime:eq(0)').val().replace(/\-|\:|\s+/g, '').substring(0, 8),
        ];

        $('input.starttime').each(function(i, e) {

            var val = $(e).val().replace(/\-|\:|\s+/g, '');
            var target = $('input.endtime:eq('+i+')').val().replace(/\-|\:|\s+/g, '');

            var startTime = val.substring(8)
            var endTime = target.substring(8);
            timeRange.push([ startTime, endTime ]);
        });


        $('div.goods-list').each(function(i, target) {

            var city = $(target).data('city');
            if (!gift[city]) gift[city] = [];
            $(target).find('input.prizeid').each(function(n, e) {
                var stack = {};
                stack.couponid = parseInt($(e).val());
                stack.amount = $(target).find('input.prize-number:eq('+n+')').val();
                console.log(stack);
                gift[city].push(stack);
            });

        });

        $.each([timeRange, dateRange, citylist, gift], function(k, v) {
            console.log(JSON.stringify(v));
        });


        var data = {prizename:prizename,icon:icon,shopid:shopid,field:field,ActivityID:ActivityID,AttributeID:AttributeID,
            timeRange:JSON.stringify(timeRange),dateRange:JSON.stringify(dateRange),citylist:JSON.stringify(citylist),gift:JSON.stringify(gift)};
        $.post(ajaxAddHandel,data,function(data){
            console.log(data)
        },'json')
    })



    //编辑活动
    $('.editSubmit').click(function () {

        if(!checkVailForm()){
            return false;
        }else{
            _data = checkVailForm();
        }

        var AlbumID = $('.image').attr('albumid');

        var ActivityID = $('.ActivityID').val();

        _data.AlbumID = AlbumID;
        _data.ActivityID = ActivityID;
        console.log(_data);

        $.post(editGraburl, _data, function (data) {
            console.log(data);
            //if (data.errno == 0) {
                standardTips('上传成功', 2);
               // window.location.href = editacturl + "&ActivityID=" + data.data.Activity.ActivityID+'&AttributeID='+data.data.Activity.attrbuteID;
          //  } else {
               // standardTips('添加失败', 2);
          //  }
        }, 'json')
    })


    ////首页列表查看
    $(".Joperate tbody").on('mouseenter', 'tr', function () {
        var html = '<span class="Jview" title="查看">查看</span>';
        $(this).find(".act-view").html(html);
    });

    $(".Joperate tbody").on('mouseleave', 'tr', function () {
        $(this).find(".act-view").html('');
    });

    //详情页，点击更新加载上传按钮
    $('.updateSite').click(function () {
        var _html = '';
        _html += '<br/>' +
            '<div id="packageInfo">' +
            '<form id="packageForm" action="' + uploadifyUrl + '" method="post" enctype="multipart/form-data">' +
            '<input type="file" id="packageupload" name="coverImg" onchange="upfilePackage(this)"></form>' +
            '<span class="form-required uploadStatus"></span>' +
            '<input type="hidden" name="packageName" id="image" class="image">' +
            '</div>';

        $('.packageList').html(_html);
        $('.packageOne').hide();
    })



    //复制链接
    $('.Joperate').on('click', '.Jcopy', function () {
        var _url;
        _url = $(this).parents('tr').find('.hidUrl').val();
        console.log(_url);
        standardAllow(_url, function () {

        });
    })

})

function checkVailForm(){
    var _Name, _Pic, _Desc;

    _Name = $('input[name=Name]').val();
    if (!checkName(_Name)) {
        standardTips('填写活动标题');
        return false;
    }

    _Pic = $('.image').val();
    if (!_Pic) {
        standardTips('上传活动图片');
        return false;
    }

    _Desc = $('.Businessdesc').val();
    if (!_Desc) {
        standardTips('填写活动说明');
        return false;
    }

    _data = {
        Name: _Name,
        Pic: _Pic,
        Desc: _Desc,
    };

    return _data;
}
/**
 *
 * @param obj
 */

function upfilePackage(obj) {
    $("#actimgForm").ajaxSubmit({
        dataType: 'json',
        beforeSend: function (XMLHttpRequest) {
            $("#coverActImg").html("上传中……");
        },
        success: function (data) {
            console.log(data);
            $("#coverActImg").html("<a href='"+data+"' target='_blank'>预览</a>");
            $(obj).parents('#actcoverImgInfo').find('.image').val(data);
            standardTips('上传成功！');

        }
    });
}



/**
 *编辑
 * @param obj
 */

function editUpfilePackage(obj) {
    $("#actimgForm").ajaxSubmit({
        dataType: 'json',
        beforeSend: function (XMLHttpRequest) {
            $("#coverActImg").html("上传中……");
        },
        success: function (data) {
            console.log(data);
            if (data.errno == 0) {
                $("#coverActImg").html("<a href='"+data.data.AlbumInfo.BgUrl+"' target='_blank'>预览</a>");
                $(obj).parents('#actcoverImgInfo').find('.grabPic a').attr('href',data.data.AlbumInfo.BgUrl);
                $(obj).parents('#actcoverImgInfo').find('.grabPic img').attr('src',data.data.AlbumInfo.BgUrl);
                $(obj).parents('#actcoverImgInfo').find('.image').val(data.data.AlbumInfo.BgUrl);
                $(obj).parents('#actcoverImgInfo').find('.image').attr('albumid',data.data.AlbumInfo.AlbumID);
                standardTips('上传成功！');
            } else {
                alert(data.error);
            }
        }
    });
}




/**
 * 检测名称是否完全
 * @param name
 * @returns {boolean}
 */
function checkName(name) {
    var _parmName, checkName;
    _parmName = $.trim(name);
    checkName = /^.{1,}$/;
    if (!checkName.test(_parmName)) {
        return false;
    }
    return true;
}



